package com.config;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.entity.SysUser;

@Component
public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	// 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.err.println("进入拦截器" + handler);
		String userJson = null;
		boolean flag = false;
		// 是执行链中的方法才会生效
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			String struuid = null;
			// 获取cookie里面的uuid
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equalsIgnoreCase("userCookie")) {
						struuid = cookie.getValue();
					}
				}
				if (struuid != null) {
					// 根据struuid，在redis中获取user信息
					userJson = stringRedisTemplate.opsForValue().get("user" + ":" + struuid);
					JSONObject redisUser = JSONObject.parseObject(userJson);
					if (redisUser != null) { // 已登录，重置redis时间
						 stringRedisTemplate.opsForValue().set("user:" + struuid, userJson, 3, TimeUnit.MINUTES);
						SysUser cookieUser = JSONObject.parseObject(userJson, SysUser.class);
						System.err.println(cookieUser);
						flag = true;
						return flag;
					}
				}
			} 
			System.out.println("需要登录");
			String servletPath = request.getServletPath();
			System.out.println(servletPath);
//			request.getRequestDispatcher("/loginForm").forward(request, response);
			 response.sendRedirect("/loginForm");
		}
		return flag;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}

}
